package com.chengyu.core.controller.ty;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.chengyu.core.component.OperationLog;
import com.chengyu.core.controller.UserBaseController;
import com.chengyu.core.domain.form.OrderSearchForm;
import com.chengyu.core.domain.form.PayBaseForm;
import com.chengyu.core.domain.form.TyOrderAddForm;
import com.chengyu.core.domain.result.*;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.*;
import com.chengyu.core.service.member.MemberService;
import com.chengyu.core.service.pay.TyPayService;
import com.chengyu.core.service.ty.TyOrderService;

import com.chengyu.core.service.ty.TyQuoteService;
import com.chengyu.core.util.RedisUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.gson.JsonArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.chengyu.core.model.TyOrder;


import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api(tags = "订单")
@Controller
@RequestMapping("/ty/order")
public class TyOrderController extends UserBaseController {

    @Autowired
    private TyOrderService orderService;

    @Autowired
    private TyPayService payService;


    @Autowired
    private MemberService memberService;

    @Autowired
    protected RedisUtil redisUtil;


    @Autowired
    private TyQuoteService quoteService;


//    @ApiOperation(value = "确认订单查询")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "goodsParams", value = "[shopId,店铺ID,skuId:商品skuId,num:购买数量]"),
//            @ApiImplicitParam(name = "groupId", value = "拼团购买方式>>-1单独购买>>0普通拼团>>其他为阶梯拼团ID")
//    })
//    @ResponseBody
//    @RequestMapping(value = {"/place"}, method = RequestMethod.POST)
//    public CommonResult<List<ShopGoodsOrder>> confirm(String goodsParams, UmsMemberAddress address, Integer groupId) throws ServiceException {
//        if (StringUtils.isBlank(goodsParams)) {
//            throw new ServiceException("order.goods");
//        }
//        List<OrderBuyDetailForm> buyDetailFormList = JSONArray.parseArray(goodsParams, OrderBuyDetailForm.class);
//        List<Integer> shopIdList = buyDetailFormList.stream().map(OrderBuyDetailForm::getShopId).distinct().collect(Collectors.toList());
//
//        List<ShopGoodsOrder> list = new ArrayList<>();
//        for (Integer shopId : shopIdList) {
//            ShopGoodsOrder goodsOrder = new ShopGoodsOrder();
//
//            List<OrderBuyDetailForm> goodsFormList = buyDetailFormList.stream().filter(detail -> detail.getShopId().equals(shopId)).collect(Collectors.toList());
//            List<ShopGoods> goodsList = new ArrayList<>();
//            List<CaculateFreightFeeForm> freightFeeFormList = new ArrayList<>();
//            for (OrderBuyDetailForm buyDetailForm : goodsFormList) {
//                PmsGoodsSku sku = goodsService.getGoodsSku(buyDetailForm.getSkuId());
//                PmsGoods goods = goodsService.getGoods(sku.getGoodsId());
//                ShopGoods shopGoods = new ShopGoods();
//                shopGoods.setGoods(goods);
//                shopGoods.setGoodsSku(sku);
//                shopGoods.setBuyNum(buyDetailForm.getNum());
//                shopGoods.setGroupId(groupId);
//                if (shopGoods.getGroupId() != null) {
//                    if (shopGoods.getGroupId() == -1) {
//                        //单独购买
//                        sku.setPrice(sku.getOriPrice());
//                        shopGoods.setGroupName("单购价");
//                    } else if (shopGoods.getGroupId() == 0) {
//                        //普通拼团
//                        shopGoods.setGroupName("拼团价");
//                    } else {
//                        //阶梯拼团
//                        PmsGoodsGroup group = goodsService.getGoodsGroup(shopGoods.getGroupId());
//                        sku.setPrice(NumberUtil.mul(sku.getPrice(), NumberUtil.div(group.getDiscounts(), 100)));
//                        shopGoods.setGroupName(group.getNum() + "人阶梯价");
//                    }
//
//                }
//                goodsList.add(shopGoods);
//                CaculateFreightFeeForm freightForm = new CaculateFreightFeeForm(goods.getFreightTemplateId(), buyDetailForm.getNum(), sku.getWeight());
//                freightFeeFormList.add(freightForm);
//            }
//            goodsOrder.setGoodsList(goodsList);
//            goodsOrder.setShopId(goodsList.get(0).getGoods().getShopId());
//            goodsOrder.setShopName(goodsList.get(0).getGoods().getShopName());
//            goodsOrder.setFreightFee(orderService.caculateFreightFee(goodsOrder.getShopId(), address, freightFeeFormList));
//            list.add(goodsOrder);
//        }
//        return CommonResult.success(list);
//    }

    @ApiOperation(value = "添加订单")
    @OperationLog
    @ResponseBody
    @RequestMapping(value = {"/add"}, method = RequestMethod.POST)
    public CommonResult<TyOrderPayResult> add(String addressToJson, String addressFromJson,ReceiptUser receiptUser,  String addFormJson) throws ServiceException {
        TyOrderAddForm addForm = JSONArray.parseObject(addFormJson, TyOrderAddForm.class);
        UmsMemberAddress addressTo = JSONArray.parseObject(addressToJson, UmsMemberAddress.class);
        UmsMemberAddress addressFrom = JSONArray.parseObject(addressFromJson, UmsMemberAddress.class);
        TyOrderPayResult result = orderService.addOrder(getCurrentMember(), addressTo, addressFrom,receiptUser, addForm);

//        JSONObject jsonObj = JSON.parseObject(jsonStr);
//        com.alibaba.fastjson.JSONObject object = JSONArray.parseObject(newJson);
//        com.alibaba.fastjson.JSONObject addressTo = JSONArray.parseObject(addressToJson);
//        com.alibaba.fastjson.JSONObject addressFrom = JSONArray.parseObject(addressFromJson);
//        TyOrderPayResult result = orderService.addOrder(getCurrentMember(), addressTo, addressFrom, addForm);
        return CommonResult.success(result);
    }

//    暂时注释掉  直接添加add
//    @ApiOperation(value = "获取拖运服务")
//    @OperationLog
//    @ResponseBody
//    @RequestMapping(value = {"/getTyService"}, method = RequestMethod.GET)
//    public CommonResult<List<TyService>> getQuoteService(@RequestParam("orderNo") String orderNo) {
//        List<TyService> result = orderService.getTyService(orderNo);
//        return CommonResult.success(result);
//    }

//    @ApiOperation(value = "选择拖运服务")
//    @OperationLog
//    @ResponseBody
//    @RequestMapping(value = {"/selectTyService"}, method = RequestMethod.POST)
//    public CommonResult<TyServiceResult> selectTyService(String orderNo, Integer type) throws ServiceException {
//        UmsMember member = getCurrentMember();
//        TyServiceResult result = orderService.selectTyService(member, orderNo, type);
//        return CommonResult.success(result);
//    }


//    @ApiOperation(value = "创建支付")
//    @OperationLog
//    @ResponseBody
//    @RequestMapping(value = {"/createPay"}, method = RequestMethod.POST)
//    public CommonResult<TyPayResult> createPay(String orderNo,Integer quoteId) throws ServiceException {
//        UmsMember member = getCurrentMember();
//        TyPayResult result = orderService.createPay(member, orderNo,quoteId);
//        return CommonResult.success(result);
//    }

    @ApiOperation(value = "创建支付")
    @OperationLog
    @ResponseBody
    @RequestMapping(value = {"/createPay"}, method = RequestMethod.POST)
    public CommonResult<TyPayResult> createPay(Integer quoteId,Integer priceId) throws ServiceException {
        UmsMember member = getCurrentMember();


//        System.out.println( quoteId) ;
//        System.out.println( priceId);

        TyPayResult result = orderService.createPay(member, quoteId,priceId);
        return CommonResult.success(result);
    }

//    @OperationLog
//    @ApiOperation(value = "支付订单")
//    @ResponseBody
//    @RequestMapping(value = {"/pay"}, method = RequestMethod.POST)
//    public CommonResult<Map<String, Object>> payOrder(String payOrderNo, PayBaseForm payBaseForm) throws Exception {
//        UmsMember member = getCurrentMember();
//        super.validateRepeat("payOrder-" + member.getId(), 5000L, "点太快了,请等待5秒再尝试~");
//        //调用支付接口
////        payBaseForm.setIp(this.getRequestIp());
//        String message = payService.orderPay(member, payOrderNo, payBaseForm);
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("payOrderNo", payOrderNo);
//        result.put("message", message);
//        return CommonResult.success(result);
//    }

    @ApiOperation(value = "支付详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "payOrderNo", value = "支付订单号"),})
    @ResponseBody
    @RequestMapping(value = "/payDetail", method = RequestMethod.GET)
    public CommonResult<CommonPayOrder> payDetail(String payOrderNo) throws Exception {
        CommonPayOrder payOrder = orderService.getPayOrder(payOrderNo);
        return CommonResult.success(payOrder);
    }


    @ApiOperation(value = "获取托运订单详情")
    @ResponseBody
    @RequestMapping(value = {"/getDetail"}, method = RequestMethod.GET)
//    public CommonResult<TyOrder> getDetail(String orderNo) throws ServiceException {
////        form.setMemberId(getCurrentMemberId());
//        TyOrder tyOrder = orderService.getOrderByOrderNo(orderNo);
//        List<String> strList1 = Arrays.asList(tyOrder.getPetType().split(","));
//        return CommonResult.success(tyOrder);
//    }
    public CommonResult<Map<String, Object>> getDetail(String orderNo) throws ServiceException {
//        form.setMemberId(getCurrentMemberId());
        TyOrder tyOrder = orderService.getOrderByOrderNo(orderNo);
//        List<String> strList1 = Arrays.asList(tyOrder.getPetType().split(","));
//        return CommonResult.success(tyOrder);


        UmsMember memberInfo = memberService.getById(tyOrder.getMemberId());
        UmsMember merMemberInfo = memberService.getById(tyOrder.getMerMemberId());




        String lnglat = (String) redisUtil.getRedisValue("ty_"+tyOrder.getOrderNo());


        if(lnglat!=null){
            String[] lnglat_arr  =lnglat.split(",");
            tyOrder.setLng(lnglat_arr[0]);
            tyOrder.setLat(lnglat_arr[1]);
        }



        Map<String, Object> result = new HashMap<>();

        result.put("order", tyOrder);
        result.put("memberInfo", memberInfo);
        result.put("merMemberInfo", merMemberInfo);

        Map<String, Object> merLocation = new HashMap<>();
        merLocation.put("longitude", 111.339805);
        merLocation.put("latitude", 30.651705);


        result.put("merLocation", merLocation);


        Integer uid = getCurrentMemberId();
        Boolean hasQuote = false;
        if(uid!=null){
            hasQuote =    quoteService.getQuoteCount(orderNo,uid)>0?true:false;
        }


        result.put("hasQuote", hasQuote);
        return CommonResult.success(result);
    }



    @OperationLog
    @ApiOperation(value = "更新定位消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/updateLngLat"}, method=RequestMethod.POST)
    public CommonResult<String> updateLngLat(String orderNo,String lng,String lat) throws ServiceException {
        redisUtil.setRedisValue("ty_"+orderNo,lng+","+lat , 1L, TimeUnit.HOURS);
        return CommonResult.success(null);
    }



    @ApiOperation(value = "获取用户拖运订单列表/我发布的订单")
    @ResponseBody
    @RequestMapping(value = {"/getMemberList"}, method = RequestMethod.GET)
    public CommonResult<CommonPage<TyOrderResult>> getMemberList(OrderSearchForm form, Integer page, Integer pageSize) throws ServiceException {
        form.setMemberId(getCurrentMemberId());
        form.setSort("id desc");
        CommonPage<TyOrderResult> list = orderService.getOrderList(form, page, pageSize);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "获取我的抢单订单列表/我的抢单")
    @ResponseBody
    @RequestMapping(value = {"/getMyChaseList"}, method = RequestMethod.GET)
    public CommonResult<CommonPage<TyOrderResult>> getMyChaseList(Integer page, Integer pageSize, String province, String city, String area) throws ServiceException {
        Integer memberId = getCurrentMemberId();
//        CommonPage<TyOrderResult> list = orderService.getMyChaseList(memberId, page, pageSize);

        OrderSearchForm form = new  OrderSearchForm();
        form.setMerMemberId(memberId);
        form.setReceiveCity(city);

        CommonPage<TyOrderResult> list = orderService.getOrderList(form, page, pageSize);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "获取拖运订单列表/抢单大厅")
    @ResponseBody
    @RequestMapping(value = {"/getList"}, method = RequestMethod.GET)
    public CommonResult<CommonPage<TyOrderResult>> getList(Integer page, Integer pageSize) throws ServiceException {


        Integer memberId = getCurrentMemberId();
        OrderSearchForm form = new  OrderSearchForm();
        form.setStatus(0);
        form.setNotMemberId(memberId);

        CommonPage<TyOrderResult> list = orderService.getOrderList(form, page, pageSize);
        return CommonResult.success(list);
    }



    @ApiOperation(value = "物流详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value="/getFreightList", method=RequestMethod.GET)
        public CommonResult<String> getDeliveryList(Integer orderId) {
//            OrderFreightResult result = orderFreightService.getOrderFreight(orderId);
        String result="";
            return CommonResult.success(result);
    }

    @OperationLog
    @ApiOperation(value = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/cancel"}, method=RequestMethod.POST)
    public CommonResult<String> cancel(Integer orderId) throws ServiceException {
        orderService.cancelOrder(getCurrentMember(), orderId);
        return CommonResult.success(null);
    }


    @OperationLog
    @ApiOperation(value = "确认开始运输")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/starttransport"}, method=RequestMethod.POST)
    public CommonResult<String> starttransport(Integer orderId) throws ServiceException {
        orderService.starttransport(getCurrentMember(), orderId);
        return CommonResult.success(null);
    }


    @OperationLog
    @ApiOperation(value = "确认送达")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/endtransport"}, method=RequestMethod.POST)
    public CommonResult<String> endtransport(Integer orderId) throws ServiceException {
        orderService.endtransport(getCurrentMember(), orderId);
        return CommonResult.success(null);
    }


    @OperationLog
    @ApiOperation(value = "修改地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
            @ApiImplicitParam(name = "addressId", value = "更换后地址ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/updateAddress"}, method=RequestMethod.POST)
    public CommonResult<String> updateAddress(Integer orderId, Integer addressId) throws ServiceException {
        orderService.updateOrderAddress(getCurrentMember(), orderId, addressId);
        return CommonResult.success(null);
    }

    @OperationLog
    @ApiOperation(value = "确认收货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID"),
    })
    @ResponseBody
    @RequestMapping(value={"/confirm"}, method=RequestMethod.POST)
    public CommonResult<String> confirmOrder(Integer orderId) throws ServiceException {
        orderService.confirmOrder(getCurrentMember(), orderId);
        return CommonResult.success(null);
    }
}
